package core.module.playCenter
{
	import core.data.DataBase;
	import core.event.TimeoutEvent;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	
	import mx.core.UIComponent;

	public class TimeBar extends UIComponent
	{
		
		private var bar:MovieClip = null;
		private var timeStamp:Number = 0;
		private var timeNow:Number = 0;
		private var timeAll:int = DataBase.getInstance().timeAll;
		
		private var timer:MovieClip = null;
		
		public function TimeBar()
		{
			super();
		}
		
		override protected function createChildren():void
		{
			super.createChildren();
			bar = new proccessBar() as MovieClip;
			addChild(bar);
			bar.gotoAndStop(1);
			
			timer = new MovieClip();
			addChild(timer);
			timer.stop();
		}
		
		public function start():void
		{
			timeStamp = new Date().getTime();
			reset();
			timer.addEventListener(Event.ENTER_FRAME,onTimer);
			timer.gotoAndPlay(1);
		}
		
		public function stop():void
		{
			timer.stop();
			timer.hasEventListener(Event.ENTER_FRAME) && timer.removeEventListener(Event.ENTER_FRAME,onTimer);
		}	
		
		public function dispose():void
		{
			stop();
		}
		
		private function onTimer(e:Event):void
		{
			if(bar.currentFrame>=60)
			{
				stop();
				dispatchEvent(new TimeoutEvent());
			}else{
				timeNow = new Date().getTime();
				bar.gotoAndStop(int(60*(timeNow-timeStamp)/timeAll));
			}
		}
		
		private function reset():void
		{
			stop();
			bar.gotoAndStop(1);
		}
	}
}